﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using wenku8.Entity;
using HtmlAgilityPack;

namespace wenku8.Parser
{
    public class BookIndexParser
    {
        public static void GetBookIndexes(string htmlPage, ObservableCollection<BookIndex> bookIndexes)
        {
            var bookIndex = new BookIndex();
            var htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(htmlPage);
            var contentNode = htmlDoc.DocumentNode;
            foreach (var tableNode in contentNode.Descendants("table")) {
                foreach (var trNode in tableNode.Descendants("tr")) {
                    if (trNode.ChildNodes.Count < 4) {
                        bookIndex = new BookIndex();
                        bookIndex.VolumnTitle = trNode.InnerText.Trim();
                        bookIndexes.Add(bookIndex);
                    }
                    else {
                        foreach (var td in trNode.ChildNodes) {
                            if (td.Name == "td" && td.InnerText != "&nbsp;") {
                                var titleAndLinkage = new TitleAndLinkage();
                                titleAndLinkage.ChapterTitle = td.InnerText.Replace("&#9450;", "⓪");
                                titleAndLinkage.InterLinkage = td.FirstChild.Attributes["href"].Value;
                                bookIndex.ChapterTitles.Add(titleAndLinkage);
                            }
                        }
                    }
                }
            }
        }
    }
}
